<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表v-loading="listLoading"-->
    <el-table :data="tableDatas" v-loading="listLoading" @selection-change="handleSelectionChange" highlight-current-row
              style="width: 100%;">
      <!--多选框-->
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="70" label="序号">
      </el-table-column>
      <el-table-column prop="name" label="角色名称">
      </el-table-column>
      <el-table-column prop="sn" label="角色编号">
      </el-table-column>

      <el-table-column label="操作" show-overflow-tooltip>
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" :disabled="this.sels.length === 0" @click="handlePatchDel">批量删除</el-button>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
                     :page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                     :total="totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加或修改界面-->
    <el-dialog title="保存角色" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item  label="角色权限">
          <el-select v-model="saveForm.permissions" multiple placeholder="请选择">
            <el-option
                v-for="item in permissions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="角色菜单">
          <div class="block">
            <el-cascader
                v-model="saveForm.menus"
                :options="menus"
                :props="{
                multiple: true,
                label:'name',
                value:'id'}"
                clearable></el-cascader>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit('saveForm')">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>

export default {
  data() {
    return {
      //1.分页查询相关数据
      totals: 0,//总记录条数
      currentPage: 1,//当前页,要传递到后台的
      pageSize: 5, //每页显示多少条
      tableDatas: [], //当前页数据
      listLoading: false,
      permissions: [],
      menus: [],

      //2.高级查询相关数据
      keyword: '',

      //3.删除相关数据

      //4.批量删除相关数据
      sels: [], //存储多选记录

      //5.添加和修改相关数据
      delFormVisible: false,
      saveFormVisible: false,
      saveForm: {
        id: null,
        name: null,
        sn: null
      },

      //6.添加和修改校验规则-表单项校验
      saveFormRules: {
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ],
        sn: [
          {required: true, message: '请输入SN码', trigger: 'blur'},
        ],
      },

    }
  },
  methods: {
    //1.分页查询相关方法
    //1.1.获取列表数据
    getTableData() {
      var data = {
        "page": this.currentPage,
        "size": this.pageSize,
        "keyword": this.keyword
      }
      this.$http.post("/role/page", data)
          .then(res => {
            console.log(res)
            if (res.data.success) {
              this.tableDatas = res.data.data.list;
              this.totals = res.data.data.total;
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(res => {
        console.log(res)
      })
    },
    //1.2.选择第几页时触发
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getTableData();
    },
    //1.3.选择每页显示记录条数时触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getTableData();
    },
    //2.高级查询相关方法
    keywordQuery() {
      this.getTableData();
    },
    //3.删除相关方法
    handleDel(row) {
      var id = row.id;
      console.log(id)
      this.$alert('是否确认删除', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          if (action === 'confirm') {
            this.$http.delete("/role/" + id).then(res => {
              if (res.data.success) {
                this.getTableData()
              } else {
                this.$message.error(res.data.msg);
              }
            }).catch(res => {

            })
          }
          this.$message({
            type: 'info',
            message: `action: ${action}`
          });
        }
      });
    },
    //4.批量删除相关方法
    //4.1.选项改变时触发
    handleSelectionChange(val) {
      this.sels = val.map(item => item.id);

    },
    //4.2.批量删除
    handlePatchDel() {
      this.$alert('是否确认删除', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          if (action === 'confirm') {
            this.$http.post("/role/deleteAll", this.sels)
                .then(res => {
                  if (res.data.success) {
                    this.getTableData();
                  } else {
                    this.$message.error(res.data.msg);
                  }
                }).catch(res => {
            })
          }
          this.$message({
            type: 'info',
            message: `action: ${action}`
          });
        }
      });
    },
    //5.添加和修改相关方法
    //5.1.点击添加弹出对话框
    handleAdd() {
      this.saveFormVisible = true;
      this.saveForm = {}
    },
    //5.2.点击修改弹出对话框
    handleEdit(row) {
      console.log(row)
      this.saveForm = Object.assign({}, row);
      let menuIds = [];
      //遍历menus[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, …],将里面每个id转成[一级路径Id,二级路径Id...]格式
      if (row.menus && Array.isArray(row.menus)) {
        row.menus.forEach(id => {
          let arrTemp = this.menuEcho(this.menus, id);
          //然后装到新数组中，遍历完成之后，每个数据都经过转换了的，然后在赋值给this.saveForm.menus左回显
          menuIds.push(arrTemp);
        });
        this.saveForm.menus = menuIds;
      }else {
        this.saveForm.menus = [];
      }
      this.saveFormVisible = true;
    },
    //5.3.提交表单数据操作数据库
    saveSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var data = this.saveForm;
          let resultMenuArr = [];
          let menuTemp = this.saveForm.menus;
          if (menuTemp && menuTemp.length > 0) {
            menuTemp.forEach(arr => {
              resultMenuArr.push(arr[arr.length - 1]);
            })
          }
          this.saveForm.menus = resultMenuArr;
          this.$http.post("/role", data)
              .then(res => {
                this.getTableData();
                this.saveFormVisible = false;
              }).catch(res => {
            this.$message.error(res.data.msg)
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    menuEcho(list, id) {
      // list：是级联选择器的options集合
      // id：你要查找的级联关系的最后一级的id
      let arr = []; // 在递归时操作的数组
      let returnArr = []; // 存放结果的数组
      let depth = 0; // 定义全局层级
      // 定义递归函数
      function childrenEach(childrenData, depthN) {
        for (var j = 0; j < childrenData.length; j++) {
          depth = depthN; // 将执行的层级赋值 到 全局层级
          arr[depthN] = childrenData[j].id;
          if (childrenData[j].id == id) {
            returnArr = arr.slice(0, depthN + 1); //将目前匹配的数组，截断并保存到结果数组，
            break;
          } else {
            if (childrenData[j].children) {
              depth++;
              childrenEach(childrenData[j].children, depth);
            }
          }
        }
        return returnArr;
      }

      return childrenEach(list, depth);
    },
    getPermissions() {
      this.$http.get("/permission")
          .then(res => {
            if (res.data.success) {
              this.permissions = res.data.data;
            }
          }).catch(res => {
      })
    },
    getMenus() {
      this.$http.get("/menu/menuTree")
          .then(res => {
            if (res.data.success) {
              this.menus = res.data.data;
            }
          }).catch(res => {
      })
    },
  },
  mounted() {
    this.getTableData();
    this.getPermissions();
    this.getMenus();
  }
}

</script>

<style scoped></style>